# -*- coding: utf-8 -*-

'''
@project : AIGateWay
@FileName: aysn_request
@Author  :linych 
@Time    :2020/11/26 14:53
@Desc  : 
'''

import ailog
from aiohttp import ClientTimeout, ClientSession, client_exceptions


class AsynClient():

    def __init__(self, time_out=5, retry=2):

        self.time_out = time_out
        self.retry = retry

    async def post(self, url, body=None, header=None):

        res = None

        timeout = ClientTimeout(total= self.time_out, connect=self.retry)
        async with ClientSession(timeout=timeout, headers=header) as session:
            try:
                async with session.post(url=url, data=body) as resp:
                    res = await resp.text()
            except client_exceptions.ServerTimeoutError as e:
                # ailog.debug(u'请求超时')
                ailog.error(u'请求超时')
            except Exception as e:
                ailog.error(u'请求失败：{}'.format(e))
                #print(u'请求失败：{}'.format(e))

        return res

    async def get(self, url, body=None, header=None):

        res = None

        timeout = ClientTimeout(total=self.time_out, connect=self.retry)
        async with ClientSession(timeout=timeout, headers=header) as session:
            try:
                async with session.get(url=url, data=body) as resp:
                    res = await resp.text()


            except client_exceptions.ServerTimeoutError as e:
                ailog.error(u'请求超时')
                #print(u'请求超时')
            except Exception as e:
                ailog.error(u'请求失败：{}'.format(e))
                #print(u'请求失败：{}'.format(e))

        return res



    async def delete(self,url,body=None,header=None):
        res = None

        timeout = ClientTimeout(total=self.time_out, connect=self.retry)
        async with ClientSession(timeout=timeout,headers=header) as session:
            try:
                async with session.delete(url=url,data=body) as resp:
                   
                    res = await resp.text()

            except client_exceptions.ServerTimeoutError as e:
                ailog.error(u'请求超时')
                #print(u'请求超时')
            except Exception as e:
                ailog.error(u'请求失败：{}'.format(e))
                #print(u'请求失败：{}'.format(e))

        return res





